const Order = require('@models/order');
const OrderItem = require('@models/order-item');
const User = require('@models/user');
const { Op } = require('sequelize');
const sequelize = require('@shared/utils/database');

class OrderService {
  /**
   * 获取订单列表
   */
  async getOrders(params) {
    const { page = 1, pageSize = 10, orderNo, status, startTime, endTime } = params;
    const where = {};

    if (orderNo) {
      where.order_no = {
        [Op.like]: `%${orderNo}%`
      };
    }

    if (status !== undefined && status !== '') {
      where.status = status;
    }

    if (startTime && endTime) {
      where.create_time = {
        [Op.between]: [startTime, endTime]
      };
    }

    const { count, rows } = await Order.findAndCountAll({
      where,
      include: [{
        model: User,
        as: 'user',
        attributes: ['id', 'name', 'phone']
      }],
      order: [['create_time', 'DESC']],
      offset: (parseInt(page) - 1) * parseInt(pageSize),
      limit: parseInt(pageSize)
    });

    return {
      list: rows,
      total: count,
      page: parseInt(page),
      pageSize: parseInt(pageSize),
    };
  }

  /**
   * 获取订单详情
   */
  async getOrderById(id) {
    const order = await Order.findByPk(id, {
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'name', 'phone']
        },
        {
          model: OrderItem,
          as: 'items'
        }
      ]
    });

    if (!order) {
      return {
        list: [],
        total: 0
      };
    }

    return {
      list: [order],
      total: 1
    };
  }

  /**
   * 更新订单
   */
  async updateOrder(id, updateData) {
    const order = await Order.findByPk(id);
    
    if (!order) {
      throw new Error('订单不存在');
    }
    
    // 检查订单状态是否可以更新
    if (updateData.status !== undefined) {
      this.validateStatusChange(order.status, updateData.status);
    }
    
    await order.update(updateData);
    
    return {
      success: true,
      message: '更新成功'
    };
  }

  /**
   * 批量更新订单状态
   */
  async batchUpdateOrders(orders) {
    const result = {
      success: 0,
      failed: 0,
      failedOrders: []
    };

    for (const orderData of orders) {
      try {
        await this.updateOrder(orderData.id, orderData);
        result.success++;
      } catch (error) {
        result.failed++;
        result.failedOrders.push({
          id: orderData.id,
          reason: error.message
        });
      }
    }

    return result;
  }

  /**
   * 验证订单状态变更是否合法
   */
  validateStatusChange(currentStatus, newStatus) {
    // 订单状态：0-待付款 1-待发货 2-待收货 3-已完成 4-已取消
    const allowedChanges = {
      0: [1, 4],    // 待付款 -> 待发货、已取消
      1: [2, 4],    // 待发货 -> 待收货、已取消
      2: [3, 4],    // 待收货 -> 已完成、已取消
      3: [],        // 已完成 -> 不能再变
      4: []         // 已取消 -> 不能再变
    };

    if (!allowedChanges[currentStatus].includes(parseInt(newStatus))) {
      throw new Error(`不能从${this.getStatusText(currentStatus)}变更为${this.getStatusText(newStatus)}`);
    }
  }

  /**
   * 获取状态文本
   */
  getStatusText(status) {
    const statusMap = {
      0: '待付款',
      1: '待发货',
      2: '待收货',
      3: '已完成',
      4: '已取消'
    };
    return statusMap[status] || '未知状态';
  }

  /**
   * 获取订单统计数据
   */
  async getOrderStats(startTime, endTime) {
    const timeCondition = {};
    
    if (startTime && endTime) {
      timeCondition.create_time = {
        [Op.between]: [startTime, endTime]
      };
    }

    // 订单总数
    const totalCount = await Order.count({
      where: timeCondition
    });

    // 订单状态分布
    const statusCounts = await Order.findAll({
      attributes: [
        'status',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      where: timeCondition,
      group: ['status']
    });

    // 订单金额统计
    const amountStats = await Order.findAll({
      attributes: [
        [sequelize.fn('SUM', sequelize.col('total_amount')), 'totalAmount'],
        [sequelize.fn('AVG', sequelize.col('total_amount')), 'avgAmount'],
        [sequelize.fn('MAX', sequelize.col('total_amount')), 'maxAmount'],
        [sequelize.fn('MIN', sequelize.col('total_amount')), 'minAmount']
      ],
      where: {
        ...timeCondition,
        status: {
          [Op.in]: [1, 2, 3] // 已支付的订单
        }
      }
    });

    const statusMap = {};
    statusCounts.forEach(item => {
      statusMap[item.status] = item.getDataValue('count');
    });

    return {
      totalCount,
      statusCounts: {
        pendingPayment: statusMap[0] || 0,
        pendingShipment: statusMap[1] || 0,
        pendingReceipt: statusMap[2] || 0,
        completed: statusMap[3] || 0,
        cancelled: statusMap[4] || 0
      },
      amountStats: amountStats[0] ? {
        totalAmount: parseFloat(amountStats[0].getDataValue('totalAmount') || 0),
        avgAmount: parseFloat(amountStats[0].getDataValue('avgAmount') || 0),
        maxAmount: parseFloat(amountStats[0].getDataValue('maxAmount') || 0),
        minAmount: parseFloat(amountStats[0].getDataValue('minAmount') || 0)
      } : {
        totalAmount: 0,
        avgAmount: 0,
        maxAmount: 0,
        minAmount: 0
      }
    };
  }
}

module.exports = new OrderService(); 